<?php
include "header.inc";

require_once "DataBase.inc";

function check_error() {
	global $errors;
	if (DataBase::last_error_number() <> 0)
		$errors .= "Error #".DataBase::last_error_number().": ".DataBase::last_error_message()."<br/>";
}

if (isset($_POST['type'])) {
	$ids = array();
	foreach ($_POST as $name=>$value)
		if (strlen($name)>3 && substr($name,0,3)=='id_')
			array_push($ids, substr($name, 3));
			
	if (isset($_POST['keep'])) {
		
		// do the merge
		$errors = "";
		$keep_id = $_POST['keep'];
		if ($keep_id == null || strlen($keep_id)==0)
			die("You didn't select anything to keep: cannot do the merge.");

		DataBase::insert("concurrency",array("operation"=>"merge","timestamp"=>time(),"username"=>$_SESSION["user"]));
		$res = DataBase::query("SELECT * FROM concurrency WHERE operation='merge' AND username<>'".$_SESSION["user"]."'");
		if ($res <> false && count($res)>0) {
			DataBase::delete("concurrency",array("operation"=>"merge","username"=>$_SESSION["user"]));
			echo "User ".$res[0]["username"]." is currently merging at the same as you!<br/>";
			echo "Only one people can merge at the same time to avoid errors in database.<br/>";
			echo "Please wait a few seconds an try again.<br/>";
			echo "<a href=''>Go back to the list</a>";
			die();
		}

		$query = "DELETE FROM ".$_POST['type']." WHERE ";
		$first = true;
		$where = "";
		foreach ($ids as $id)
			if ($id <> $keep_id) {
				if ($first) $first = false; else $where .= " OR";
				$where .= " !!!=".$id; 
			}
		$query .= str_replace("!!!",$_POST['type']."_id",$where);
		DataBase::query($query);
		check_error();		
		
		switch ($_POST['type']) {
			case 'province':
				DataBase::query("UPDATE applicant SET applicant_origin_province_id=".$keep_id." WHERE ".str_replace("!!!","applicant_origin_province_id",$where));
				check_error();
				DataBase::query("UPDATE applicant SET applicant_parents_province_id=".$keep_id." WHERE ".str_replace("!!!","applicant_parents_province_id",$where));
				check_error();
				DataBase::query("UPDATE exam_center SET province_id=".$keep_id." WHERE ".str_replace("!!!","province_id",$where));
				check_error();
				break;
			case 'high_school':
				DataBase::query("UPDATE applicant SET high_school_id=".$keep_id." WHERE ".str_replace("!!!","high_school_id",$where));
				check_error();
				break;
			case 'exam_center':
				DataBase::query("UPDATE applicant_exam_room_beta SET exam_center_id=".$keep_id." WHERE ".str_replace("!!!","exam_center_id",$where));
				check_error();
				break;
			case 'ngo':
				DataBase::query("UPDATE applicant SET ngo_id=".$keep_id." WHERE ".str_replace("!!!","ngo_id",$where));
				check_error();
				break;
			default:
				$errors .= "Invalid type '".$_POST['type']."'.<br/>";
		}
		DataBase::delete("concurrency",array("operation"=>"merge","username"=>$_SESSION["user"]));
		if (strlen($errors)==0)
			echo "Merge successfully done.";
		else
			echo "Some errors occured during the merge:<br/>".$errors;
		echo "<br/><a href='check_typing.php'>Go back to the list</a>";
	} else {
		// ask which to keep
		echo "<form name='keep' method='post'>";
		echo "<input type='hidden' name='type' value='".$_POST['type']."'/>";
		foreach ($ids as $id)
			echo "<input type='hidden' name='id_".$id."' value='1'/>";
		echo "You want to merge the following entries into a single one. Please select the one you want to keep:<br/>";
		$list = DataBase::select($_POST['type'], null, null);
		foreach ($ids as $id) {
			echo "<input type='radio' name='keep' value='".$id."'/>";
			$found = false;
			foreach ($list as $row)
				if ($row[$_POST['type']."_id"]==$id) {
					echo $row[$_POST['type']."_name"];
					$found = true;
					break;
				}
			if (!$found) {
				echo "<br/>An element doesn't exist anymore!<br/>This may be due to someone else merging at the same time as you.<br/>Please <a href=''>come back to the list</a> and try again.";
				die();
			}
			echo "<br/>";
		}
		echo "<button type='submit'>Merge</button>";
		echo "</form>";
	}
} else {

echo "<h1>Exam Centers For This Selection Campaign</h1>";
echo "<form name='exam_center' method='post'>";
echo "<input type='hidden' name='type' value='exam_center'/>";
$list = DataBase::query("SELECT exam_center.*,province.province_name FROM exam_center LEFT JOIN province ON exam_center.province_id=province.province_id WHERE exam_center.selection_campaign_id=".$_SESSION["campaign_id"]." ORDER BY province.province_name,exam_center.exam_center_name ASC");
if ($list <> false)
foreach ($list as $row)
	echo "<input type='checkbox' name='id_".$row["exam_center_id"]."'/> ".$row["exam_center_name"]." (Province ".$row["province_name"].")<br/>";
echo "<button type='submit'>Merge selected exam centers into a single one</button>";
echo "</form>";
echo "<hr width=100%/>";
	
echo "<h1>Provinces</h1>";
echo "<form name='province' method='post'>";
echo "<input type='hidden' name='type' value='province'/>";
$list = DataBase::select("province", null, null,"province_name ASC");
if ($list <> false)
foreach ($list as $row)
	echo "<input type='checkbox' name='id_".$row["province_id"]."'/> ".$row["province_name"]."<br/>";
echo "<button type='submit'>Merge selected provinces into a single one</button>";
echo "</form>";
echo "<hr width=100%/>";

echo "<h1>High Schools</h1>";
echo "<form name='high_school' method='post'>";
echo "<input type='hidden' name='type' value='high_school'/>";
$list = DataBase::select("high_school", null, null,"high_school_name ASC");
if ($list <> false)
foreach ($list as $row)
	echo "<input type='checkbox' name='id_".$row["high_school_id"]."'/> ".$row["high_school_name"]."<br/>";
echo "<button type='submit'>Merge selected high schools into a single one</button>";
echo "</form>";
echo "<hr width=100%/>";

echo "<h1>NGOs</h1>";
echo "<form name='ngo' method='post'>";
echo "<input type='hidden' name='type' value='ngo'/>";
$list = DataBase::select("ngo", null, null,"ngo_name ASC");
if ($list <> false)
foreach ($list as $row)
	echo "<input type='checkbox' name='id_".$row["ngo_id"]."'/> ".$row["ngo_name"]."<br/>";
echo "<button type='submit'>Merge selected NGOs into a single one</button>";
echo "</form>";
echo "<hr width=100%/>";

}

include "footer.inc";
?>